package com.wbf.demo.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wbf.demo.domain.Subject;
import com.wbf.demo.util.ServletTool;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆成功处理类
 * @author guangdao
 */
@Data
@Component
public class JsonAuthSuccessHandler implements AuthenticationSuccessHandler {


    private final Logger logger = LoggerFactory.getLogger(JsonAuthSuccessHandler.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 登陆成功后返回token等内容
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        request.getSession();
        String sessionId = request.changeSessionId();
        Subject userDetails = (Subject) authentication.getPrincipal();
        //设置token k-v缓存
//        request.getSession().setAttribute(
//                FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, userDetails.getId() + "");
        Map<String, Object> map = new HashMap<>(3);
        map.put("token", sessionId);
        map.put("nickName",userDetails.getNickName());
        map.put("menu",userDetails.getMenuList());
        map.put("role",userDetails.getRoleList());
        ServletTool.writeJSONStr(response, new ObjectMapper().writeValueAsString(map));
    }


}
